const app = getApp()
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    plans: [],
    loading: false,
    page: 1,
    limit: 10,
    hasMore: true,
    status: '',
    orderId: '',
    statusList: [
      { value: '', label: '全部状态' },
      { value: 0, label: '未开始' },
      { value: 1, label: '进行中' },
      { value: 2, label: '已暂停' },
      { value: 3, label: '已完成' }
    ]
  },

  onLoad(options) {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/production-plans/production-plans')) {
      return
    }
    
    if (options.orderId) {
      this.setData({
        orderId: options.orderId
      })
    }
    this.loadPlans()
  },

  onShow() {
    this.refreshPlans()
  },

  onPullDownRefresh() {
    this.refreshPlans()
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMorePlans()
    }
  },

  // 加载生产计划列表
  loadPlans() {
    if (this.data.loading) return
    
    this.setData({ loading: true })
    
    const params = {
      page: this.data.page,
      limit: this.data.limit
    }
    
    if (this.data.status !== '') {
      params.status = this.data.status
    }
    
    if (this.data.orderId) {
      params.order_id = this.data.orderId
    }
    
    app.request({
      url: '/getProductionPlans',
      method: 'GET',
      data: params
    }).then(res => {
      if (res.code === 1) {
        const newPlans = res.data.rows || []
        const plans = this.data.page === 1 ? newPlans : [...this.data.plans, ...newPlans]
        
        // 调试信息：检查订单数据和状态
        if (newPlans.length > 0) {
          console.log('生产计划数据示例:', newPlans[0])
          console.log('订单信息:', newPlans[0].order)
          console.log('状态信息:', {
            status: newPlans[0].status,
            statusText: this.getStatusText(newPlans[0].status),
            statusColor: this.getStatusColor(newPlans[0].status)
          })
        }
        
        this.setData({
          plans: plans,
          hasMore: newPlans.length >= this.data.limit,
          loading: false
        })
      } else {
        wx.showToast({
          title: res.msg || '加载失败',
          icon: 'none'
        })
        this.setData({ loading: false })
      }
    }).catch(err => {
      console.error('加载生产计划失败:', err)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
      this.setData({ loading: false })
    })
  },

  // 刷新列表
  refreshPlans() {
    this.setData({
      page: 1,
      hasMore: true
    })
    this.loadPlans()
  },

  // 加载更多
  loadMorePlans() {
    this.setData({
      page: this.data.page + 1
    })
    this.loadPlans()
  },

  // 状态筛选
  onStatusChange(e) {
    const status = e.detail.value
    this.setData({
      status: status,
      page: 1,
      hasMore: true
    })
    this.loadPlans()
  },

  // 查看详情
  viewDetail(e) {
    const planId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/production-plan-detail/production-plan-detail?id=${planId}`
    })
  },

  // 创建生产计划
  createPlan() {
    wx.navigateTo({
      url: '/pages/create-production-plan/create-production-plan'
    })
  },

  // 从订单生成
  generateFromOrder() {
    wx.navigateTo({
      url: '/pages/generate-production-plan/generate-production-plan'
    })
  },

  // 分配工序
  allocateProcess(e) {
    const planId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/allocate-production-plan/allocate-production-plan?planId=${planId}`
    })
  },

  // 查看进度
  viewProgress(e) {
    const planId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/production-plan-progress/production-plan-progress?planId=${planId}`
    })
  },

  // 查看仪表板
  viewDashboard() {
    wx.navigateTo({
      url: '/pages/production-dashboard/production-dashboard'
    })
  },

  // 开始计划
  startPlan(e) {
    const planId = e.currentTarget.dataset.id
    wx.showModal({
      title: '确认开始',
      content: '确定要开始这个生产计划吗？',
      success: (res) => {
        if (res.confirm) {
          this.updatePlanStatus(planId, 'start')
        }
      }
    })
  },

  // 暂停计划
  pausePlan(e) {
    const planId = e.currentTarget.dataset.id
    wx.showModal({
      title: '确认暂停',
      content: '确定要暂停这个生产计划吗？',
      success: (res) => {
        if (res.confirm) {
          this.updatePlanStatus(planId, 'pause')
        }
      }
    })
  },

  // 恢复计划
  resumePlan(e) {
    const planId = e.currentTarget.dataset.id
    wx.showModal({
      title: '确认恢复',
      content: '确定要恢复这个生产计划吗？',
      success: (res) => {
        if (res.confirm) {
          this.updatePlanStatus(planId, 'resume')
        }
      }
    })
  },

  // 完成计划
  completePlan(e) {
    const planId = e.currentTarget.dataset.id
    wx.showModal({
      title: '确认完成',
      content: '确定要完成这个生产计划吗？',
      success: (res) => {
        if (res.confirm) {
          this.updatePlanStatus(planId, 'complete')
        }
      }
    })
  },

  // 更新计划状态
  updatePlanStatus(planId, action) {
    wx.showLoading({ title: '处理中...' })
    
    const actionMap = {
      start: 'startProductionPlan',
      pause: 'pauseProductionPlan',
      resume: 'resumeProductionPlan',
      complete: 'completeProductionPlan'
    }
    
    app.request({
      url: `/${actionMap[action]}`,
      method: 'POST',
      data: { id: planId }
    }).then(res => {
      wx.hideLoading()
      if (res.code === 1) {
        wx.showToast({
          title: res.msg || '操作成功',
          icon: 'success'
        })
        this.refreshPlans()
      } else {
        wx.showToast({
          title: res.msg || '操作失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.hideLoading()
      console.error('更新计划状态失败:', err)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    })
  },

  // 编辑计划
  editPlan(e) {
    const planId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/edit-production-plan/edit-production-plan?id=${planId}`
    })
  },

  // 删除计划
  deletePlan(e) {
    const planId = e.currentTarget.dataset.id
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个生产计划吗？删除后不可恢复。',
      success: (res) => {
        if (res.confirm) {
          this.doDeletePlan(planId)
        }
      }
    })
  },

  // 执行删除
  doDeletePlan(planId) {
    wx.showLoading({ title: '删除中...' })
    
    app.request({
      url: '/deleteProductionPlan',
      method: 'POST',
      data: { id: planId }
    }).then(res => {
      wx.hideLoading()
      if (res.code === 1) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        })
        this.refreshPlans()
      } else {
        wx.showToast({
          title: res.msg || '删除失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.hideLoading()
      console.error('删除生产计划失败:', err)
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      })
    })
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      0: '未开始',
      1: '进行中',
      2: '已暂停',
      3: '已完成'
    }
    return statusMap[status] || '未知'
  },

  // 获取状态颜色
  getStatusColor(status) {
    const colorMap = {
      0: '#999',      // 未开始 - 灰色
      1: '#07c160',   // 进行中 - 绿色
      2: '#ff976a',   // 已暂停 - 橙色
      3: '#1989fa'    // 已完成 - 蓝色
    }
    return colorMap[status] || '#999'
  }
})
